package cn.yeziji.file.utils;

import cn.yeziji.forum.basic.file.WebUploader;
import cn.yeziji.forum.basic.file.WebUploaderFileInfo;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
import java.util.Set;

/**
 * 文件工具
 *
 * @author gzkemays
 * @since 2022/11/03 6:19 PM
 */
public class FileHandlerUtils {
  /**
   * 根据缓存中得 map 获取上传文件的信息
   *
   * @param map map
   * @return 传文件信息
   */
  public static WebUploaderFileInfo getMaxFileInfoByMap(Map<Object, Object> map) {
    Set<Object> keys = map.keySet();
    int max = 0;
    // 获取最大的分片
    for (Object key : keys) {
      int keyInt = Integer.parseInt(key.toString());
      if (max < keyInt) {
        max = keyInt;
      }
    }
    Object obj = map.get(max);
    if (obj == null) {
      return null;
    }
    return new WebUploaderFileInfo((WebUploader.ChuckEntity) obj);
  }

  public static InputStream generatePDFImageStream(File file) {
    try (PDDocument pdfDocument = PDDocument.load(file)) {
      PDFRenderer pdfRenderer = new PDFRenderer(pdfDocument);
      // 提取的页码
      int pageNumber = 0;
      // 以300 dpi 读取存入 BufferedImage 对象
      int dpi = 100;
      // Renderer类的renderImage()方法在特定页面中渲染图像
      BufferedImage buffImage = pdfRenderer.renderImageWithDPI(pageNumber, dpi, ImageType.RGB);
      return fileCase(buffImage);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
   * 文件转换将BufferedImage转换成MultipartFile：为了文件上传
   *
   * @param image 图片 buffer
   * @return inputStream
   */
  private static InputStream fileCase(BufferedImage image) {
    try {
      // 创建一个 ByteArrayOutputStream
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      // 把 BufferedImage 写入 ByteArrayOutputStream
      ImageIO.write(image, "jpg", os);
      // ByteArrayOutputStream 转成 InputStream
      return new ByteArrayInputStream(os.toByteArray());
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
}
